//mysql 查询获取结果
#include <stdio.h>
#include <stdlib.h>
#include "mysql.h"

int main(int argc,char *argv[])
{
	int res = 0;
	int i=0;

	//初始化mysql
	MYSQL *mysql = mysql_init(NULL);
	if(mysql == NULL)
	{
		printf("mysql init is error,[%d]\n",mysql_errno(mysql));
		return -1;
	}

	//mysql链接
	MYSQL *conn = mysql_real_connect(mysql,"127.0.0.1","root","root","mem",0,NULL,0);
	if(conn != 0)
	{
		printf("mysql connect is error,[%s]",mysql_error(conn));
	}

	printf("mysql connect is ok\n");

	//mysql的查询
	char sSql[256] = "select *from menu";
	res = mysql_query(conn,sSql);
	if(res != 0)
	{
		printf("mysql query is error\n");
	}
	printf("mysql query is ok\n");
	
	//获取结果集行数
	//unsigned int mysql_field_count(MYSQL *mysql)
	//从返回的结果集中获取有多少列
	//unsigned int mysql_num_fields(MYSQL_RES *result)
	int num = mysql_field_count(conn);

	//msyql 拿到数据
	MYSQL_RES *result = mysql_store_result(conn);

	//先打印表头
	MYSQL_FIELD *fields = NULL;
	fields = mysql_fetch_fields(result);
	for(i=0;i<num;i++)
	{
		printf("%s\t",fields[i].name);
	}
	printf("\n");

	//msyql的row数据
	MYSQL_ROW row = NULL;
	while((row = mysql_fetch_row(result)))
	{
		i = 0;
		for(i=0;i<num;i++)
		{
			printf("%s\t", row[i]);
		}
		printf("\n");
	}

	mysql_free_result(result);
	return 0;
}